package com.yc.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平锁
 * @author yuancan
 *
 */
public class TestFairLock {
	
	static Lock lock = new ReentrantLock(true);//true：公平

	public static void main(String[] args) {
		TestFairLock tfl = new TestFairLock();
		tfl.m1();
		
	}
	
	public void m1() {
		for (int i = 0; i < 5; i++) {
			new Thread(new MyRunable(), "T" + i).start();
		}
		
		System.out.println("==");

	}
	
	static class MyRunable implements Runnable {

		@Override
		public void run() {
			
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} 
			
			for (int i = 0; i < 3; i++) {
				lock.lock();
				System.out.println("----" + Thread.currentThread().getName());
				lock.unlock();
			}
			
		}
		
	}

}

